// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  const openid = wxContext.OPENID
  
  try {
    console.log('开始初始化测试数据');
    
    // 1. 创建必要的集合
    const collections = ['images', 'user_likes', 'user_favorites', 'comments'];
    
    for (const collection of collections) {
      try {
        await db.createCollection(collection);
        console.log(`成功创建集合: ${collection}`);
      } catch (err) {
        // 集合可能已存在，忽略错误
        console.log(`集合 ${collection} 可能已存在`);
      }
    }
    
    // 2. 检查是否已有测试数据
    const imagesCount = await db.collection('images').count();
    
    if (imagesCount.total > 0) {
      console.log('已存在图片数据，跳过初始化');
      return {
        success: true,
        message: '已存在数据，跳过初始化'
      };
    }
    
    // 3. 创建测试图片数据
    const imageUrls = [
      'cloud://cloudbase-1.636c-cloudbase-1-4g5layzue1a7ec6e/images/image1.jpg',
      'cloud://cloudbase-1.636c-cloudbase-1-4g5layzue1a7ec6e/images/image2.jpg',
      'cloud://cloudbase-1.636c-cloudbase-1-4g5layzue1a7ec6e/images/image3.jpg'
    ];
    
    const titles = [
      '山间湖泊风景',
      '未来城市',
      '古堡夜景'
    ];
    
    const descriptions = [
      '宁静湖泊与山脉的完美结合',
      '霓虹灯照耀下的未来都市街景',
      '月光下的神秘古堡'
    ];
    
    const now = db.serverDate();
    
    // 创建图片
    for (let i = 0; i < imageUrls.length; i++) {
      const imageData = {
        _openid: openid,
        fileID: imageUrls[i],
        title: titles[i],
        description: descriptions[i],
        prompt: '使用AI生成的' + titles[i],
        negativePrompt: '',
        style: 'realistic',
        size: '1024*1024',
        likeCount: 0,
        favoriteCount: 0,
        commentCount: 0,
        viewCount: 0,
        tags: titles[i].split(' '),
        category: i % 2 === 0 ? 'landscape' : 'abstract',
        status: 'active',
        createTime: now,
        updateTime: now
      };
      
      const result = await db.collection('images').add({
        data: imageData
      });
      
      console.log(`成功创建图片: ${result._id}`);
    }
    
    return {
      success: true,
      message: '测试数据初始化成功'
    };
  } catch (error) {
    console.error('初始化测试数据失败:', error);
    return {
      success: false,
      message: '初始化测试数据失败',
      error
    };
  }
} 